<?php
/**
 * Created by PhpStorm.
 * User: 55371
 * Date: 2017/10/21
 * Time: 18:01
 */

namespace App\Service\Order;

use DB;

use Carbon\Carbon;

use App\Models\Bill\Bill;

use App\Models\Bill\BillPay;

use App\Models\Bill\BillGoods;

use App\Models\Bill\BillTrace;

use Illuminate\Support\Facades\Redis as Redis;

abstract class PtOrderService
{

    protected $billGoodsData = [];

    protected $bill; //订单数据

    protected $bill_no; //订单号

    protected $datetime; //下单时间

    protected $creator; //创建人

    protected $pcustID; //会员号

    protected $custID; //会员名

    protected $openId; //微信粉丝openId

    protected $cardNo; //会员卡号

    protected $pay_status; //支付状态

    protected $insert = []; //待保存的数据

    public function __construct($bill, $creator = 'system')
    {

        $this->datetime = Carbon::now();
        $this->bill_no = generate_seqno('seqno_bill', null, true);
        $this->bill = $bill;
        $this->creator = $creator;
        $this->pcustID = $bill['pcustID'];
        $this->custID = $bill['custID'];
        $this->cardNo = $bill['cardNo'];
        $this->openId = $bill['openId'];

        //支付状态
        $this->pay_status = 0;
        $this->bill['master']['payed_time'] = null;
        if( $this->bill['master']['bill_payable'] == 0 ){  //说明订单已经无需支付（优惠券、积分、余额等抵扣）
            $this->bill['master']['payed_time'] = Carbon::now();
            $this->pay_status = 1;
        } else if ( $this->bill['master']['bill_points_money'] > 0 || $this->bill['master']['bill_balance_money'] > 0 ) {
            $this->pay_status = 2;
        }

        if (!isset($this->bill['master']['invoiceID'])) {
            $this->bill['master']['invoiceID'] = 0;
        }

        if (!isset($this->bill['master']['invoice_type'])) {
            $this->bill['master']['invoice_type'] = '';
        }

        if (!isset($this->bill['master']['invoice_content_id'])) {
            $this->bill['master']['invoice_content_id'] = 0;
        }

        if (!isset($this->bill['master']['invoice_title_type'])) {
            $this->bill['master']['invoice_title_type'] = '';
        }

        if (!isset($this->bill['master']['invoice_title'])) {
            $this->bill['master']['invoice_title'] = '';
        }

        if (!isset($this->bill['master']['invoice_content'])) {
            $this->bill['master']['invoice_content'] = '';
        }

        if (!isset($this->bill['master']['invoice_amount'])) {
            $this->bill['master']['invoice_amount'] = '';
        }

        if (!isset($this->bill['master']['bill_stock_type'])) {
            $this->bill['master']['bill_stock_type'] = 1;
        }

        if (!isset($this->bill['master']['split_type'])) {
            $this->bill['master']['split_type'] = 1;
        }

        if (!isset($this->bill['master']['send_deliver_type'])) {
            $this->bill['master']['send_deliver_type'] = 0;
        }

        if (!isset($this->bill['master']['bill_cross_border'])) {
            $this->bill['master']['bill_cross_border'] = '';
        }

        if (!isset($this->bill['master']['added_value_tax'])) {
            $this->bill['master']['added_value_tax'] = '';
        }

        if (!isset($this->bill['master']['consumption_tax'])) {
            $this->bill['master']['consumption_tax'] = '';
        }

        if (!isset($this->bill['master']['identification_card'])) {
            $this->bill['master']['identification_card'] = '';
        }

        if (!isset($this->bill['master']['identification_name'])) {
            $this->bill['master']['identification_name'] = '';
        }

        if (!isset($this->bill['master']['tuan_status'])) {
            $this->bill['master']['tuan_status'] = 0;
        }

        if (!isset($this->bill['master']['parent_bill_no'])) {
            $this->bill['master']['parent_bill_no'] = 0;
        }

    }

    /**
     * 创建订单主表数据
     * @return bool
     */
    protected function createMaster()
    {

        $bill = new Bill();
        $bill->uuid = makeUuid();
        $bill->timeStamp = $this->datetime;
        $bill->creator = $this->creator;
        $bill->createTime = $this->datetime;
        $bill->bill_no = $this->bill_no;
        $bill->pcustID = $this->bill['pcustID'];
        $bill->custID = $this->bill['custID'];
        $bill->bill_status = 0;
        $bill->bill_return_status = 0;
        $bill->bill_refund_status = 0;
        $bill->bill_logistics_status = 0;
        $bill->bill_totalMoney = $this->bill['master']['bill_totalMoney'];
        $bill->bill_totalPaid = $this->bill['master']['bill_totalPaid'];
        $bill->bill_tariff_money = $this->bill['master']['bill_tariff_money'];
        $bill->bill_totalPoints = $this->bill['master']['bill_totalPoints'];
        $bill->bill_pointsPrice = $this->bill['master']['bill_pointsPrice'];
        $bill->bill_subtract_money = $this->bill['master']['bill_subtract_money'];
        $bill->bill_points_money = $this->bill['master']['bill_points_money'];
        $bill->bill_balance_money = $this->bill['master']['bill_balance_money'];
        $bill->bill_coupon_money = $this->bill['master']['bill_coupon_money'];
        $bill->bill_card_money = 0;
        $bill->bill_payable = $this->bill['master']['bill_payable'];
        $bill->bill_total_amount = $this->bill['master']['bill_total_amount'];
        $bill->bill_withdraw_amount = 0;
        $bill->deliverid = $this->bill['master']['deliverid'];
        $bill->deliver_name = $this->bill['master']['deliver_name'];
        $bill->deliver_province = $this->bill['master']['deliver_province'];
        $bill->deliver_provinceid = $this->bill['master']['deliver_provinceid'];
        $bill->deliver_city = $this->bill['master']['deliver_city'];
        $bill->deliver_cityid = $this->bill['master']['deliver_cityid'];
        $bill->deliver_county = $this->bill['master']['deliver_county'];
        $bill->deliver_countyid = $this->bill['master']['deliver_countyid'];
        $bill->deliver_address = $this->bill['master']['deliver_address'];
        $bill->deliver_mobile = $this->bill['master']['deliver_mobile'];
        $bill->deliver_phone = $this->bill['master']['deliver_phone'];
        $bill->sendTypeID = $this->bill['master']['sendTypeID'];
        $bill->sendTypeName = $this->bill['master']['sendTypeName'];
        $bill->ziti = $this->bill['master']['ziti'];
        $bill->send_region_id = $this->bill['master']['send_region_id'];
        $bill->send_region_name = $this->bill['master']['send_region_name'];
        $bill->deliver_fee = $this->bill['master']['deliver_fee'];
        $bill->deliver_feePaid = $this->bill['master']['deliver_feePaid'];
        $bill->pay_type = $this->bill['master']['pay_type'];
        $bill->payTypeID = $this->bill['master']['payTypeID'];
        $bill->payTypeName = $this->bill['master']['payTypeName'];
        $bill->pay_status = $this->pay_status;
        $bill->payed_time = $this->bill['master']['payed_time'];
        $bill->pay_id_str = $this->bill['master']['pay_id_str'];
        $bill->goods_name_str = $this->bill['master']['goods_name_str'];
        $bill->billPlatform = $this->bill['master']['billPlatform'];
        $bill->billChannel = $this->bill['master']['billChannel'];
        $bill->billType = $this->bill['master']['billType'];
        $bill->invoice = $this->bill['master']['invoice'];
        $bill->invoiceID = $this->bill['master']['invoiceID'];
        $bill->invoice_type = $this->bill['master']['invoice_type'];
        $bill->invoice_title_type = $this->bill['master']['invoice_title_type'];
        $bill->invoice_title = $this->bill['master']['invoice_title'];
        $bill->invoice_content_id = $this->bill['master']['invoice_content_id'];
        $bill->invoice_content = $this->bill['master']['invoice_content'];
        $bill->invoice_amount = $this->bill['master']['invoice_amount'];
        $bill->package_no = null;
        $bill->bill_stock_type = $this->bill['master']['bill_stock_type'];
        $bill->split_type = $this->bill['master']['split_type'];
        $bill->parent_bill_no = $this->bill['master']['parent_bill_no'];
        $bill->mallID = $this->bill['master']['mallID'];
        $bill->mallCode = $this->bill['master']['mallCode'];
        $bill->mallName = $this->bill['master']['mallName'];
        $bill->barcode = null;
        $bill->activity_id = $this->bill['master']['activity_id'];
        $bill->remark = $this->bill['master']['remark'];
        $bill->is_comment = 0;
        $bill->is_enter_erp = 0;
        $bill->express_number = null;
        $bill->express_company = null;
        $bill->pickup_start_time = $this->bill['master']['pickup_start_time'];
        $bill->pickup_end_time = $this->bill['master']['pickup_end_time'];
        $bill->send_time = $this->bill['master']['send_time'];
        $bill->bill_cancel_reason = null;
        $bill->send_deliver_type = $this->bill['master']['send_deliver_type'];
        $bill->verify_time = null;
        $bill->print_num = 0;
        $bill->supplier_id = $this->bill['master']['supplier_id'];
        $bill->zt_id = $this->bill['master']['zt_id'];
        $bill->zt_name = $this->bill['master']['zt_name'];
        $bill->zt_code = $this->bill['master']['zt_code'];
        $bill->bill_cross_border = $this->bill['master']['bill_cross_border'];
        $bill->added_value_tax = $this->bill['master']['added_value_tax'];
        $bill->consumption_tax = $this->bill['master']['consumption_tax'];
        $bill->identification_card = $this->bill['master']['identification_card'];
        $bill->identification_name = $this->bill['master']['identification_name'];
        $bill->tuan_status = $this->bill['master']['tuan_status'];

        $this->insert['bill_master'][] = $bill;

        return true;

    }


    /**
     * 创建订单商品信息
     * @return bool
     */
    protected function createGoods()
    {

        $goods_name = [];

        foreach( $this->bill['goods'] as &$goods ) {

            if ( !isset($goods['recordPrice']) ) {
                $goods['recordPrice'] = 0;
            }
            if ( !isset($goods['goods_pointsPrice']) ) {
                $goods['goods_pointsPrice'] = 0;
            }

            $goods_name[] = $goods['goodsName'];

            $bill_goods = new BillGoods();
            $bill_goods->uuid = makeUuid();
            $bill_goods->timeStamp = $this->datetime;
            $bill_goods->createTime = $this->datetime;
            $bill_goods->creator = $this->creator;
            $bill_goods->bill_no = $this->bill_no;
            $bill_goods->bill_goods_no = generate_seqno('seqno_bill_goods', null, true);
            $bill_goods->goods_goodsID = $goods['goodsID'];
            $bill_goods->goods_postID = $goods['postID'];
            $bill_goods->product_code = $goods['product_code'];
            $bill_goods->goods_name = $goods['goodsName'];
            $bill_goods->goods_spec = $goods['spec'];
            $bill_goods->goods_amount = $goods['goods_amount'];
            $bill_goods->goods_storePrice = $goods['salePrice'];
            $bill_goods->goods_purchasePrice = $goods['price'];
            $bill_goods->goods_marketPrice = $goods['marketPrice'];
            $bill_goods->goods_pointsPrice = $goods['goods_pointsPrice'];
            $bill_goods->goods_points = $goods['salePoints'];
            $bill_goods->goods_weight = $goods['goodsWeight'];
            $bill_goods->goods_from = $goods['goods_from'];
            $bill_goods->goods_groupID = $goods['goods_groupID'];
            $bill_goods->goods_status = 1;
            $bill_goods->goods_time = null;
            $bill_goods->goods_delivercount = 0;
            $bill_goods->goods_remark = $goods['goods_remark'];
            $bill_goods->comment_flg = 0;
            $bill_goods->goods_withdrawAmount = 0;
            $bill_goods->goods_rejectionAmount = 0;
            $bill_goods->virtual_id = $goods['virtual_id'];
            $bill_goods->recordPrice = $goods['recordPrice'];
            $this->insert['bill_goods'][] = $bill_goods;
        }

        $this->bill['goods_name_str'] = implode(',', $goods_name);

        return true;

    }


    /**
     * 创建订单支付信息
     * @return bool
     */
    protected function createPay()
    {

        $pay_id = [];
        $pay_name = [];

        foreach( $this->bill['pay'] as &$pay ){

            if ( !isset($pay['deduct_amount']) ) {
                $pay['deduct_amount'] = 0;
            }
            if ( !isset($pay['pay_code']) ) {
                $pay['pay_code'] = null;
            }
            if ( !isset($pay['pay_time']) ) {
                $pay['pay_time'] = null;
            }
            if ( !isset($pay['paid_confirm_status']) ) {
                $pay['paid_confirm_status'] = 0;
            }

            $bill_pay = new BillPay();
            $bill_pay->uuid = makeUuid();
            $bill_pay->timeStamp = $this->datetime;
            $bill_pay->createTime = $this->datetime;
            $bill_pay->creator = $this->creator;
            $bill_pay->bill_no = $this->bill_no;
            $bill_pay->payTypeID = $pay['payTypeID'];
            $bill_pay->payTypeName = $pay['payTypeName'];
            $bill_pay->type = $pay['type'];
            $bill_pay->pay_amount = $pay['pay_amount'];
            $bill_pay->deduct_amount = $pay['deduct_amount'];
            $bill_pay->pay_code = $pay['pay_code'];
            $bill_pay->pay_time = $pay['pay_time'];
            $bill_pay->paid_confirm_status = $pay['paid_confirm_status'];
            $bill_pay->paid_confirmer = null;
            $bill_pay->paid_confirm_time = null;
            $this->insert['bill_pay'][] = $bill_pay;
            $pay_id[] = $pay['payTypeID'];
            $pay_name[] = $pay['payTypeName'];

        }

        $this->bill['pay_id_str'] = implode(',', $pay_id);
        $this->bill['pay_name_str'] = implode(',', $pay_name);

        return true;

    }

    /**
     * 创建订单轨迹信息
     * @return bool
     */
    protected function createTrace()
    {

        $bill_trace = new BillTrace();
        $bill_trace->uuid = makeUuid();
        $bill_trace->timeStamp = $this->datetime;
        $bill_trace->createTime = $this->datetime;
        $bill_trace->creator = $this->creator;
        $bill_trace->bill_no = $this->bill_no;
        $bill_trace->bill_status = 0;
        $bill_trace->content = '您的订单已提交，请等待系统确认';
        $this->insert['bill_trace'][] = $bill_trace;

        return true;

    }


    protected function checkoutBillGoods()
    {

        //组合商品
        if ( isset($this->bill['goods']['group']) && !empty($this->bill['goods']['group']) ) {
            foreach( $this->bill['goods']['group'] as $key=>$group ) {

                if ( isset($group['is_buy']) && $group['is_buy'] == 0 ) {
                    continue;
                }

                if ( isset($group['goods']) && !empty($group['goods']) ) {

                    $cross_border = 0;
                    foreach($group['goods'] as $g) {
                        if ($g['goodsType'] == 3)
                            $cross_border = 1;
                    }
                    if (($this->bill['check_type'] == 2 && !$cross_border) || ($this->bill['check_type'] == 1 && $cross_border))
                        continue;

                    foreach( $group['goods'] as $goods_array ) {
                        $goods['goods_amount'] = $group['group_amount'];

                        $this->createBillGoodsData($goods_array, 9, $group['goods_groupID']);
                    }
                }
            }
        }

        //保存订单商品信息（普通商品）
        if (isset($this->bill['goods']['general']) && !empty($this->bill['goods']['general'])) {

            foreach ($this->bill['goods']['general'] as $general) {

                if ($this->bill['check_type'] == 2 && $general['goodsType'] != 3 || $this->bill['check_type'] == 1 && $general['goodsType'] == 3) {
                    continue;
                }

                $general['addPoints'] = 0;

                $this->createBillGoodsData( $general, 1 );

            }

        }

        //积分兑换商品
        if ( isset($bill_data['goods']['points']) && !empty($bill_data['goods']['points'])) {
            foreach( $bill_data['goods']['points'] as $points ) {
                $this->createBillGoodsData($points, 4, $points['goods_groupID']);
            }
        }

        //秒杀立即购买
        if ( isset($bill_data['goods']['flashSale']) && !empty($bill_data['goods']['flashSale']) ) {
            foreach ( $bill_data['goods']['flashSale'] as $flashSale ){
                $this->createBillGoodsData($flashSale, 11, $flashSale['goods_groupID']);
            }
        }

        //预售商品
        if (isset($bill_data['goods']['pre_sale']) && !empty($bill_data['goods']['pre_sale'])) {
            foreach($bill_data['goods']['pre_sale'] as $pre_sale) {
                $this->createBillGoodsData($pre_sale, 7, $pre_sale['goods_groupID']);
            }
        }

        return true;

    }

    protected function createBillGoodsData( $goods_data, $goods_from, $goods_groupID = 0 )
    {

        $goodsID = $goods_data['goodsID'];
        $postID = $goods_data['postID'];

        if ($goods_from == 3) {
            $goods_data['goods_amount'] = $goods_data['saleAmount'];
            $goods_data['price'] = 0;
            $goods_data['addPoints'] = 0;
            $goods_data['salePoints'] = 0;
            $goods_data['goodsWeight'] = 0;
        } else if ($goods_from == 13) {
            $goods_data['addPoints'] = 0;
            $goods_data['salePoints'] = 0;
            $goods_data['goodsWeight'] = 0;
        }

        $this->bill['goods'][] = array(
            'goods_goodsID' => $goodsID,
            'goods_postID' => $postID,
            'goods_name' => $goods_data['goodsName'],
            'goods_spec' => $goods_data['spec'],
            'goods_amount' => $goods_data['goods_amount'],
            'goods_marketPrice' => $goods_data['marketPrice'],
            'goods_storePrice' => $goods_data['salePrice'],
            'goods_purchasePrice' => $goods_data['price'],
            'goods_pointsPrice' => $goods_data['addPoints'],
            'recordPrice' => $goods_data['recordPrice'],
            'goods_points' => $goods_data['salePoints'],
            'goods_from' => $goods_from,
            'goods_groupID' => $goods_groupID,
            'virtual_id' => $goods_data['virtual_id'],
            'supplier_id' => isset($goods_data['supplier_id']) ? $goods_data['supplier_id'] : 1,
            'goods_status' => 1,
            'goodsWeight' => $goods_data['goodsWeight'],
            'product_code' => $goods_data['product_code'],
            'time_slot_id' => isset($goods_data['time_slot_id']) && !empty($goods_data['time_slot_id']) ? $goods_data['time_slot_id'] : 0
        );

        if (isset($goods_data['gift']) && !empty($goods_data['gift'])) {
            foreach($goods_data['gift'] as $gift) {
                if (!ebsig_is_int($gift['saleAmount']))
                    continue;
                $this->bill['goods'][]  = array(
                    'goods_goodsID' => $gift['goodsID'],
                    'goods_postID' => $gift['postID'],
                    'goods_name' => $gift['goodsName'],
                    'goods_spec' => $gift['spec'],
                    'goods_amount' => $gift['saleAmount'],
                    'goods_marketPrice' => $gift['salePrice'],
                    'goods_storePrice' => $gift['salePrice'],
                    'goods_purchasePrice' => 0,
                    'goods_pointsPrice' => 0,
                    'goods_points' => 0,
                    'goods_from' => 2,
                    'goods_groupID' => 0,
                    'goods_status' => 1,
                    'goodsWeight' => 0,
                    'recordPrice' => 0,
                    'product_code' => $gift['product_code']
                );
                $this->bill['master']['bill_total_mount'] += $gift['saleAmount'];

                //如果是赠品的话，添加到检查商品库存的范围中去
                if ($this->bill['check_type'] != 3 && ($goods_from == 1 || $goods_from == 4)) {
                    if (isset($this->billGoodsData['store'][$gift['goodsID']])) {
                        $this->billGoodsData['store'][$gift['goodsID']]['goods_amount'] += $gift['saleAmount'];
                    } else {
                        $this->billGoodsData['store'][$gift['goodsID']] = array(
                            'goodsID' => $gift['goodsID'],
                            'goodsName' => $gift['goodsName'],
                            'goods_amount' => $gift['saleAmount'],
                            'product_code' => $gift['product_code'],
                            'product_spec' => $gift['product_spec'],
                            'goodsType' => isset($gift['goodsType'])?$gift['goodsType']:1
                        );
                    }
                }
            }
        }

        //用于检查库存的商品数据
        if ($this->bill['check_type'] != 3 && ($goods_from == 1 || $goods_from == 4)) {
            if (isset($this->billGoodsData['store'][$goodsID])) {
                $this->billGoodsData['store'][$goodsID]['goods_amount'] += $goods_data['goods_amount'];
            } else {
                $this->billGoodsData['store'][$goodsID] = array(
                    'goodsID' => $goodsID,
                    'goodsName' => $goods_data['goodsName'],
                    'goods_amount' => $goods_data['goods_amount'],
                    'product_code' => $goods_data['product_code'],
                    'product_spec' => $goods_data['product_spec'],
                    'goodsType' => isset($goods_data['goodsType'])?$goods_data['goodsType']:1
                );
            }
        }

        //用于检查订单促销的商品数据
        if (in_array($goods_from, array(1, 4, 7, 11, 12))) {
            $this->billGoodsData['promotion'][] = array(
                'postID' => $postID,
                'price' => $goods_data['price'],
                'goods_amount' => $goods_data['goods_amount'],
                'type' => 'general'
            );
        }

        //用于跨境购商品数据
        if (in_array($goods_from, array(1, 4, 6, 7, 9, 10, 11, 12, 13))) {
            $this->billGoodsData['goods_tax'][] = $goods_data;
        }
    }

    abstract function submit();

}